<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" placeholder="请输入内容" class="search-main" clearable />
      <el-button v-permission="'park:building:list'" type="primary" @click="search">查询</el-button>
    </div>
    <el-button v-permission="'park:building:add_edit'" type="primary" @click="addBuilding">添加楼宇</el-button>
    <el-button @click="exportToExcel">导出Excel</el-button>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="buildingList">
        <el-table-column type="index" label="序号" :index="indexMethod" />
        <el-table-column label="楼宇名称" prop="name" align="center" />
        <el-table-column label="层数" prop="floors" width="180" />
        <el-table-column label="在管面积(m²)" width="120" prop="area" />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column label="状态" prop="status" align="center">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button v-permission="'park:building:add_edit'" size="mini" type="text" @click="editBuilding(scope.row)">编辑</el-button>
            <el-button v-permission="'park:building:remove'" size="mini" type="text" @click="deleteBuilding(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div class="page-container">
      <el-pagination
        :current-page="params.page"
        :page-size="params.pageSize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加楼宇弹框 -->
    <el-dialog
      :title="addForm.id ? '修改楼宇' : '新增楼宇' "
      :visible="dialogVisible"
      width="580px"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area"><template #append>m²</template></el-input>
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice"><template #append>元/m²</template></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBuildingListAPI, createBuildingListAPI, updateBuildingAPI, delBuildingListAPI } from '@/api/Park/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      params: {
        page: 1,
        pageSize: 3,
        name: ''
      },
      total: 0,
      buildingList: [],
      dialogVisible: false,
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [{ required: true, message: '请输入楼宇名称', trigger: 'blur' }],
        floors: [{ required: true, message: '请输入楼宇层数', trigger: 'blur' }],
        area: [{ required: true, message: '请输入楼宇面积', trigger: 'blur' }],
        propertyFeePrice: [{ required: true, message: '请输入楼宇物业费', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getBuildingList()
  },
  methods: {
    // 导出表单
    async exportToExcel() {
      const res = await getBuildingListAPI(this.params)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      const sheetHeader = ['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']
      // 处理数据
      const sheetData = res.data.rows.map(item => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [sheetHeader], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 添加楼宇按钮
    addBuilding() {
      this.dialogVisible = true
    },
    // 关闭表单
    closeDialog() {
      this.dialogVisible = false
      // 清空表单
      this.$refs.addForm.resetFields()
      this.addForm = {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      }
    },
    // 提交表单按钮
    confirmAdd() {
      this.$refs.addForm.validate(async valid => {
        if (!valid) return
        if (this.addForm.id) {
          const { id, name, floors, area, propertyFeePrice } = this.addForm
          const editForm = {
            id,
            name,
            floors,
            area,
            propertyFeePrice
          }
          await updateBuildingAPI(editForm)
          this.$message.success('修改楼宇成功')
          this.closeDialog()
          this.getBuildingList()
        } else {
          await createBuildingListAPI(this.addForm)
          this.$message.success('添加楼宇成功')
          this.closeDialog()
          this.getBuildingList()
        }
      })
    },
    // 编辑按钮
    async editBuilding(row) {
      this.dialogVisible = true
      // 获取表单详细数据
      const { id, area, floors, name, propertyFeePrice } = row
      this.addForm = {
        id, area, floors, name, propertyFeePrice
      }
    },
    // 删除按钮
    deleteBuilding(id) {
      this.$confirm('你确定要删除此数据吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await delBuildingListAPI(id)
        this.$message.success('删除成功')
        this.getBuildingList()
      })
    },
    // 获取楼宇列表数据
    async getBuildingList() {
      const res = await getBuildingListAPI(this.params)
      this.buildingList = res.data.rows
      this.total = res.data.total
    },
    // 切换分页
    handleCurrentChange(page) {
      this.params.page = page
      this.getBuildingList()
    },
    // 查询按钮
    search() {
      this.params.page = 1
      this.getBuildingList()
    },
    // 计算序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 租赁状态适配
    formatStatus(status) {
      const statusMap = {
        0: '租赁中',
        1: '闲置中'
      }
      return statusMap[status]
    }
  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-label {
    width: 100px;
  }
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
</style>
